<template>
  <div class="system-config">
    <!-- 系统配置管理 -->
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <el-icon><Tools /></el-icon>
          <span>系统配置管理</span>
          <div class="header-actions">
            <el-button @click="loadConfig" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button @click="resetToDefaults">
              <el-icon><RefreshLeft /></el-icon>
              恢复默认
            </el-button>
            <el-button type="danger" @click="handleRestart" :loading="restarting">
              <el-icon><RefreshRight /></el-icon>
              重启主程序
            </el-button>
            <el-button type="primary" @click="saveConfig" :loading="saving">
              <el-icon><Check /></el-icon>
              保存配置
            </el-button>
          </div>
        </div>
      </template>

      <el-tabs v-model="activeTab" type="card" class="config-tabs">
        <!-- 基础配置 -->
        <el-tab-pane label="基础配置" name="basic">
          <el-form
            ref="basicFormRef"
            :model="systemConfig.basic"
            :rules="basicRules"
            label-width="140px"
            size="default"
            class="config-form"
          >
            <div class="form-section">
              <h4 class="section-title">系统信息</h4>
              
              <el-form-item label="系统名称" prop="system_name" required>
                <el-input 
                  v-model="systemConfig.basic.system_name" 
                  placeholder="EMS 能源管理系统"
                  clearable
                />
                <div class="form-tip">系统显示名称，用于界面标题和日志标识</div>
              </el-form-item>

              <el-form-item label="系统版本" prop="version">
                <el-input 
                  v-model="systemConfig.basic.version" 
                  placeholder="v1.0.0"
                  disabled
                />
                <div class="form-tip">当前系统版本号（只读）</div>
              </el-form-item>

              <el-form-item label="设备ID" prop="device_id" required>
                <el-input 
                  v-model="systemConfig.basic.device_id" 
                  placeholder="网关设备唯一标识"
                  clearable
                />
                <div class="form-tip">网关设备的唯一标识符，用于MQTT连接和设备识别</div>
              </el-form-item>

              <el-form-item label="工作模式" prop="work_mode" required>
                <el-select 
                  v-model="systemConfig.basic.work_mode" 
                  placeholder="选择工作模式"
                  style="width: 100%"
                >
                  <el-option label="采集模式" value="collector" />
                  <el-option label="网关模式" value="gateway" />
                  <el-option label="边缘计算模式" value="edge" />
                </el-select>
                <div class="form-tip">系统运行模式，影响功能启用和资源分配</div>
              </el-form-item>
            </div>

            <div class="form-section">
              <h4 class="section-title">网络配置</h4>
              
              <el-form-item label="监听端口" prop="listen_port" required>
                <el-input-number
                  v-model="systemConfig.basic.listen_port"
                  :min="1024"
                  :max="65535"
                  style="width: 100%"
                  placeholder="Web服务端口"
                />
                <div class="form-tip">Web管理界面监听端口</div>
              </el-form-item>

              <el-form-item label="API端口" prop="api_port" required>
                <el-input-number
                  v-model="systemConfig.basic.api_port"
                  :min="1024"
                  :max="65535"
                  style="width: 100%"
                  placeholder="API服务端口"
                />
                <div class="form-tip">REST API服务端口</div>
              </el-form-item>

              <el-form-item label="WebSocket端口" prop="websocket_port">
                <el-input-number
                  v-model="systemConfig.basic.websocket_port"
                  :min="1024"
                  :max="65535"
                  style="width: 100%"
                  placeholder="WebSocket端口"
                />
                <div class="form-tip">实时数据推送WebSocket端口</div>
              </el-form-item>
            </div>
          </el-form>
        </el-tab-pane>

        <!-- 数据采集配置 -->
        <el-tab-pane label="数据采集" name="collection">
          <el-form
            ref="collectionFormRef"
            :model="systemConfig.collection"
            :rules="collectionRules"
            label-width="140px"
            size="default"
            class="config-form"
          >
            <div class="form-section">
              <h4 class="section-title">采集参数</h4>
              
              <el-form-item label="采集间隔(秒)" prop="interval" required>
                <el-input-number
                  v-model="systemConfig.collection.interval"
                  :min="1"
                  :max="3600"
                  style="width: 100%"
                  placeholder="数据采集间隔"
                />
                <div class="form-tip">设备数据采集的时间间隔</div>
              </el-form-item>

              <el-form-item label="超时时间(毫秒)" prop="timeout" required>
                <el-input-number
                  v-model="systemConfig.collection.timeout"
                  :min="1000"
                  :max="30000"
                  :step="1000"
                  style="width: 100%"
                  placeholder="连接超时"
                />
                <div class="form-tip">设备连接和数据读取超时时间</div>
              </el-form-item>

              <el-form-item label="重试次数" prop="retry_count" required>
                <el-input-number
                  v-model="systemConfig.collection.retry_count"
                  :min="0"
                  :max="10"
                  style="width: 100%"
                  placeholder="失败重试次数"
                />
                <div class="form-tip">采集失败后的重试次数</div>
              </el-form-item>

              <el-form-item label="并发数" prop="max_concurrent">
                <el-input-number
                  v-model="systemConfig.collection.max_concurrent"
                  :min="1"
                  :max="100"
                  style="width: 100%"
                  placeholder="最大并发采集数"
                />
                <div class="form-tip">同时进行数据采集的最大设备数量</div>
              </el-form-item>

              <el-form-item label="自动重连" prop="auto_reconnect">
                <el-switch 
                  v-model="systemConfig.collection.auto_reconnect"
                  active-text="启用"
                  inactive-text="禁用"
                />
                <div class="form-tip">设备离线时自动尝试重新连接</div>
              </el-form-item>
            </div>

            <div class="form-section">
              <h4 class="section-title">数据处理</h4>
              
              <el-form-item label="数据缓存" prop="enable_cache">
                <el-switch 
                  v-model="systemConfig.collection.enable_cache"
                  active-text="启用"
                  inactive-text="禁用"
                />
                <div class="form-tip">启用数据缓存提高性能</div>
              </el-form-item>

              <el-form-item label="缓存大小(MB)" prop="cache_size" v-if="systemConfig.collection.enable_cache">
                <el-input-number
                  v-model="systemConfig.collection.cache_size"
                  :min="10"
                  :max="1000"
                  style="width: 100%"
                  placeholder="缓存大小"
                />
                <div class="form-tip">数据缓存的内存大小限制</div>
              </el-form-item>

              <el-form-item label="数据压缩" prop="enable_compression">
                <el-switch 
                  v-model="systemConfig.collection.enable_compression"
                  active-text="启用"
                  inactive-text="禁用"
                />
                <div class="form-tip">启用数据压缩节省存储空间</div>
              </el-form-item>
            </div>
          </el-form>
        </el-tab-pane>

        <!-- 日志配置 -->
        <el-tab-pane label="日志配置" name="logging">
          <el-form
            ref="loggingFormRef"
            :model="systemConfig.logging"
            :rules="loggingRules"
            label-width="140px"
            size="default"
            class="config-form"
          >
            <div class="form-section">
              <h4 class="section-title">日志设置</h4>
              
              <el-form-item label="日志级别" prop="level" required>
                <el-select 
                  v-model="systemConfig.logging.level" 
                  placeholder="选择日志级别"
                  style="width: 100%"
                >
                  <el-option label="DEBUG" value="debug" />
                  <el-option label="INFO" value="info" />
                  <el-option label="WARN" value="warn" />
                  <el-option label="ERROR" value="error" />
                </el-select>
                <div class="form-tip">系统日志记录级别</div>
              </el-form-item>

              <el-form-item label="日志文件路径" prop="file_path">
                <el-input 
                  v-model="systemConfig.logging.file_path" 
                  placeholder="/var/log/ems/system.log"
                  clearable
                />
                <div class="form-tip">日志文件存储路径</div>
              </el-form-item>

              <el-form-item label="单文件大小(MB)" prop="max_file_size">
                <el-input-number
                  v-model="systemConfig.logging.max_file_size"
                  :min="1"
                  :max="100"
                  style="width: 100%"
                  placeholder="日志文件大小限制"
                />
                <div class="form-tip">单个日志文件的最大大小</div>
              </el-form-item>

              <el-form-item label="保留文件数" prop="max_files">
                <el-input-number
                  v-model="systemConfig.logging.max_files"
                  :min="1"
                  :max="100"
                  style="width: 100%"
                  placeholder="日志文件保留数量"
                />
                <div class="form-tip">系统保留的历史日志文件数量</div>
              </el-form-item>

              <el-form-item label="控制台输出" prop="console_output">
                <el-switch 
                  v-model="systemConfig.logging.console_output"
                  active-text="启用"
                  inactive-text="禁用"
                />
                <div class="form-tip">是否同时输出日志到控制台</div>
              </el-form-item>
            </div>

            <div class="form-section">
              <h4 class="section-title">远程日志</h4>
              
              <el-form-item label="远程日志" prop="enable_remote">
                <el-switch 
                  v-model="systemConfig.logging.enable_remote"
                  active-text="启用"
                  inactive-text="禁用"
                />
                <div class="form-tip">启用远程日志收集服务</div>
              </el-form-item>

              <template v-if="systemConfig.logging.enable_remote">
                <el-form-item label="远程地址" prop="remote_host">
                  <el-input 
                    v-model="systemConfig.logging.remote_host" 
                    placeholder="192.168.1.100"
                    clearable
                  />
                  <div class="form-tip">远程日志服务器地址</div>
                </el-form-item>

                <el-form-item label="远程端口" prop="remote_port">
                  <el-input-number
                    v-model="systemConfig.logging.remote_port"
                    :min="1"
                    :max="65535"
                    style="width: 100%"
                    placeholder="远程端口"
                  />
                  <div class="form-tip">远程日志服务器端口</div>
                </el-form-item>
              </template>
            </div>
          </el-form>
        </el-tab-pane>

        <!-- 安全配置 -->
        <el-tab-pane label="安全设置" name="security">
          <el-form
            ref="securityFormRef"
            :model="systemConfig.security"
            :rules="securityRules"
            label-width="140px"
            size="default"
            class="config-form"
          >
            <div class="form-section">
              <h4 class="section-title">访问控制</h4>
              
              <el-form-item label="启用认证" prop="enable_auth">
                <el-switch 
                  v-model="systemConfig.security.enable_auth"
                  active-text="启用"
                  inactive-text="禁用"
                />
                <div class="form-tip">Web界面访问认证</div>
              </el-form-item>

              <template v-if="systemConfig.security.enable_auth">
                <el-form-item label="用户名" prop="username" required>
                  <el-input 
                    v-model="systemConfig.security.username" 
                    placeholder="管理员用户名"
                    clearable
                  />
                  <div class="form-tip">Web管理界面登录用户名</div>
                </el-form-item>

                <el-form-item label="密码" prop="password" required>
                  <el-input 
                    v-model="systemConfig.security.password" 
                    type="password"
                    placeholder="管理员密码"
                    show-password
                    clearable
                  />
                  <div class="form-tip">Web管理界面登录密码</div>
                </el-form-item>

                <el-form-item label="会话超时(分钟)" prop="session_timeout">
                  <el-input-number
                    v-model="systemConfig.security.session_timeout"
                    :min="5"
                    :max="1440"
                    style="width: 100%"
                    placeholder="会话超时时间"
                  />
                  <div class="form-tip">登录会话的超时时间</div>
                </el-form-item>
              </template>

              <el-form-item label="IP白名单" prop="allow_ips">
                <el-input 
                  v-model="systemConfig.security.allow_ips" 
                  type="textarea"
                  :rows="3"
                  placeholder="192.168.1.0/24&#10;10.0.0.0/8&#10;0.0.0.0/0"
                />
                <div class="form-tip">允许访问的IP地址段，每行一个（CIDR格式）</div>
              </el-form-item>
            </div>

            <div class="form-section">
              <h4 class="section-title">HTTPS配置</h4>
              
              <el-form-item label="启用HTTPS" prop="enable_https">
                <el-switch 
                  v-model="systemConfig.security.enable_https"
                  active-text="启用"
                  inactive-text="禁用"
                />
                <div class="form-tip">启用HTTPS安全连接</div>
              </el-form-item>

              <template v-if="systemConfig.security.enable_https">
                <el-form-item label="证书文件" prop="cert_file">
                  <el-input 
                    v-model="systemConfig.security.cert_file" 
                    placeholder="/etc/ssl/certs/server.crt"
                    clearable
                  />
                  <div class="form-tip">SSL证书文件路径</div>
                </el-form-item>

                <el-form-item label="私钥文件" prop="key_file">
                  <el-input 
                    v-model="systemConfig.security.key_file" 
                    placeholder="/etc/ssl/private/server.key"
                    type="password"
                    show-password
                    clearable
                  />
                  <div class="form-tip">SSL私钥文件路径</div>
                </el-form-item>

                <el-form-item label="HTTPS端口" prop="https_port">
                  <el-input-number
                    v-model="systemConfig.security.https_port"
                    :min="1024"
                    :max="65535"
                    style="width: 100%"
                    placeholder="HTTPS端口"
                  />
                  <div class="form-tip">HTTPS服务监听端口</div>
                </el-form-item>
              </template>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 配置预览 -->
    <el-card class="preview-card" v-if="showPreview">
      <template #header>
        <div class="card-header">
          <el-icon><View /></el-icon>
          <span>配置预览</span>
          <el-button type="text" @click="showPreview = false">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </template>
      
      <el-input
        :model-value="configPreview"
        type="textarea"
        :rows="15"
        readonly
        class="config-preview"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { 
  Tools, Refresh, RefreshLeft, RefreshRight, Check, View, Close
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { configAPI, systemAPI } from '@/utils/api'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const activeTab = ref('basic')
const showPreview = ref(false)
const restarting = ref(false)

// 表单引用
const basicFormRef = ref()
const collectionFormRef = ref()
const loggingFormRef = ref()
const securityFormRef = ref()

// 系统配置数据
const systemConfig = reactive({
  basic: {
    system_name: 'EMS 能源管理系统',
    version: 'v1.0.0',
    device_id: '',
    work_mode: 'gateway',
    listen_port: 8080,
    api_port: 8081,
    websocket_port: 8082
  },
  collection: {
    interval: 30,
    timeout: 5000,
    retry_count: 3,
    max_concurrent: 10,
    auto_reconnect: true,
    enable_cache: true,
    cache_size: 100,
    enable_compression: false
  },
  logging: {
    level: 'info',
    file_path: '/var/log/ems/system.log',
    max_file_size: 10,
    max_files: 5,
    console_output: true,
    enable_remote: false,
    remote_host: '',
    remote_port: 514
  },
  security: {
    enable_auth: false,
    username: 'admin',
    password: '',
    session_timeout: 60,
    allow_ips: '0.0.0.0/0',
    enable_https: false,
    cert_file: '',
    key_file: '',
    https_port: 8443
  }
})

// 原始配置备份
let originalConfig = {}

// 表单验证规则
const basicRules = {
  system_name: [
    { required: true, message: '请输入系统名称', trigger: 'blur' }
  ],
  device_id: [
    { required: true, message: '请输入设备ID', trigger: 'blur' },
    { min: 3, max: 50, message: '设备ID长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  work_mode: [
    { required: true, message: '请选择工作模式', trigger: 'change' }
  ],
  listen_port: [
    { required: true, message: '请输入监听端口', trigger: 'blur' },
    { type: 'number', min: 1024, max: 65535, message: '端口范围1024-65535', trigger: 'blur' }
  ],
  api_port: [
    { required: true, message: '请输入API端口', trigger: 'blur' },
    { type: 'number', min: 1024, max: 65535, message: '端口范围1024-65535', trigger: 'blur' }
  ]
}

const collectionRules = {
  interval: [
    { required: true, message: '请输入采集间隔', trigger: 'blur' },
    { type: 'number', min: 1, max: 3600, message: '采集间隔范围1-3600秒', trigger: 'blur' }
  ],
  timeout: [
    { required: true, message: '请输入超时时间', trigger: 'blur' },
    { type: 'number', min: 1000, max: 30000, message: '超时时间范围1000-30000毫秒', trigger: 'blur' }
  ],
  retry_count: [
    { required: true, message: '请输入重试次数', trigger: 'blur' },
    { type: 'number', min: 0, max: 10, message: '重试次数范围0-10', trigger: 'blur' }
  ]
}

const loggingRules = {
  level: [
    { required: true, message: '请选择日志级别', trigger: 'change' }
  ]
}

const securityRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur', when: () => systemConfig.security.enable_auth }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur', when: () => systemConfig.security.enable_auth },
    { min: 6, message: '密码长度至少6位', trigger: 'blur', when: () => systemConfig.security.enable_auth }
  ]
}

// 计算属性
const configPreview = computed(() => {
  return JSON.stringify(systemConfig, null, 2)
})

// 方法
const loadConfig = async () => {
  try {
    loading.value = true
    const config = await configAPI.getSystemConfig()
    Object.assign(systemConfig, config)
    originalConfig = JSON.parse(JSON.stringify(config))
  } catch (error) {
    ElMessage.error('加载系统配置失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const handleRestart = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重启主程序吗？重启过程中服务将短暂中断。',
      '确认重启',
      {
        confirmButtonText: '立即重启',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    restarting.value = true
    await systemAPI.restart()
    ElMessage.success('重启命令已下发，系统将自动重新启动')
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      return
    }
    const message = error?.message || '重启失败'
    ElMessage.error(message)
  } finally {
    restarting.value = false
  }
}

const saveConfig = async () => {
  // 验证所有表单
  const forms = [basicFormRef, collectionFormRef, loggingFormRef, securityFormRef]
  const validations = await Promise.allSettled(
    forms.map(ref => ref.value?.validate().catch(() => false))
  )

  const hasInvalidForm = validations.some(result => 
    result.status === 'rejected' || result.value === false
  )

  if (hasInvalidForm) {
    ElMessage.error('请检查配置信息')
    return
  }

  try {
    saving.value = true
    
    await configAPI.updateSystemConfig(systemConfig)
    originalConfig = JSON.parse(JSON.stringify(systemConfig))
    
    ElMessage.success('系统配置保存成功')
  } catch (error) {
    ElMessage.error('保存系统配置失败: ' + error.message)
  } finally {
    saving.value = false
  }
}

const resetToDefaults = () => {
  ElMessageBox.confirm(
    '确定要恢复默认配置吗？所有未保存的修改将丢失。',
    '恢复默认配置',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 恢复默认配置
    Object.assign(systemConfig, {
      basic: {
        system_name: 'EMS 能源管理系统',
        version: 'v1.0.0',
        device_id: '',
        work_mode: 'gateway',
        listen_port: 8080,
        api_port: 8081,
        websocket_port: 8082
      },
      collection: {
        interval: 30,
        timeout: 5000,
        retry_count: 3,
        max_concurrent: 10,
        auto_reconnect: true,
        enable_cache: true,
        cache_size: 100,
        enable_compression: false
      },
      logging: {
        level: 'info',
        file_path: '/var/log/ems/system.log',
        max_file_size: 10,
        max_files: 5,
        console_output: true,
        enable_remote: false,
        remote_host: '',
        remote_port: 514
      },
      security: {
        enable_auth: false,
        username: 'admin',
        password: '',
        session_timeout: 60,
        allow_ips: '0.0.0.0/0',
        enable_https: false,
        cert_file: '',
        key_file: '',
        https_port: 8443
      }
    })
    
    // 清空表单验证
    forms.forEach(ref => ref.value?.clearValidate())
    
    ElMessage.success('已恢复默认配置')
  }).catch(() => {
    // 用户取消
  })
}

// 生命周期
onMounted(() => {
  loadConfig()
})
</script>

<style scoped>
.system-config {
  max-width: 1000px;
  margin: 0 auto;
}

.config-card {
  margin-bottom: 20px;
}

.preview-card {
  position: sticky;
  top: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.header-actions {
  margin-left: auto;
  display: flex;
  gap: 12px;
}

.config-tabs {
  margin-top: 20px;
}

.config-tabs :deep(.el-tabs__content) {
  padding: 20px 0;
}

.config-form {
  max-width: 800px;
}

.form-section {
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e8e8e8;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 20px 0;
  color: #262626;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title::before {
  content: '';
  width: 4px;
  height: 16px;
  background: #1890ff;
  border-radius: 2px;
}

.form-tip {
  color: #8c8c8c;
  font-size: 12px;
  margin-top: 4px;
  line-height: 1.4;
}

.config-preview {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.config-preview :deep(.el-textarea__inner) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  line-height: 1.6;
  background-color: #f8f8f8;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-input-number) {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .system-config {
    margin: 0 10px;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .header-actions .el-button {
    width: 100%;
  }
  
  .config-form {
    max-width: none;
  }
  
  :deep(.el-form-item__label) {
    width: 100px !important;
  }
  
  .preview-card {
    position: static;
  }
}

@media (max-width: 576px) {
  :deep(.el-tabs__nav-wrap) {
    overflow-x: auto;
  }
  
  :deep(.el-tabs__item) {
    flex-shrink: 0;
  }
}
</style>
